var mongoose = require('mongoose');
var Users = require("../models/mod_user");
var rc4=require("../models/mod_password")

//新增
exports.user_create = function (req, res, next) {
    //解决特殊情况
    if(typeof(req.body.problem)!="object"){
        req.body.problem = JSON.parse(req.body.problem);
    }
    const user = new Users(req.body);
    user.save().then((data) => {
        res.json(data);
    }).catch(err => res.json(err));
}
//修改
exports.user_update = function (req, res, next) {
    //解决特殊情况
    if(typeof(req.body.problem)!="object"){
        req.body.problem = JSON.parse(req.body.problem);
    }
    const id = req.params.id;
    Users.findByIdAndUpdate(id, { $set: req.body }, { new: true }).then(data => {
        res.json(data);
    });
}
//删除一个
exports.user_delete = function (req, res, next) {
    const id = req.params.id;
    Users.findByIdAndDelete(id).then(data => {
        res.json(data);
    });
}
//删除多个
exports.user_removes = function (req, res, next) {
    const ids = req.body.ids.split(",");
    Users.remove({ _id: { $in: ids } }).then(data => {
        res.json(data);
    });
}
//查询指定数据
exports.user_list_id = function (req, res, next) {
    const id = req.params.id;
    Users.findById(id).then(data => {
        res.json(data);
    });
}
//查询所有数据
exports.lm = function (req, res, next) {
    Users.find().then(data => {
        res.json(data);
    });
}
//查询密文指定数据
exports.user_list_special_id = function (req, res, next) {
    const id=JSON.parse(rc4(req.params.id));
    Users.findById(id).then(data => {
        res.json(data.username);
    });
}
//查询所有（分页）
exports.user_list = function (req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 10;
    var search = req.body.search ? req.body.search : '';
    var sex = req.body.sex ? req.body.sex : '';

    var options = {
        page: +page,
        limit: +rows,
        sort: { _id: -1 }
    }


    var queryparams={};
    if(req.body.search&&search.length>0){
        queryparams={
            $or: [
                {"age":{$eq:isNaN(Number.parseInt(search))?'':Number.parseInt(search)}},
                {"username":new RegExp(search,'i')},
                {"password":new RegExp(search,'i')},
                {"email":new RegExp(search,'i')},
                {"address":new RegExp(search,'i')},
                {"hobbies":{$elemMatch:{$eq:search}}},
                {"drink":{$eq:search}},
                {"problem.title":new RegExp(search,"i")},
                {"problem.question":new RegExp(search,"i")}
            ],
            $and: [{"sex":{$eq:sex}}]
        }
    }else if(req.body.sex&&sex.length>0){
        queryparams={
            $and: [{"sex":{$eq:sex}}]
        }
    }
    // console.log(search);
    
    Users.paginate(queryparams, options, function (err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}


//查询用户
exports.login = function (req, res, next) {
    const username = req.body.username;
    const password = req.body.password;
    Users.find({username,password}).then(data => {
        // res.json(data);
        //加密
        if(data.length>0){
            const ds=data[0]._id;
            res.cookie(rc4("UsernameId"), rc4(JSON.stringify(ds)), { maxAge: 24 * 60 * 60 * 1000});
            // console.log(req.cookies,rc4("UsernameId"))
            res.json({data:"ok",message:"success",key:rc4("UsernameId")});
        }else{
            res.json({data:"error",message:"fail"});
        }
    });
}


  exports.token = function (req, res, next) {
        var value=req.body.value;
         if(req.body.value!=""){
            const _id=rc4(value);
            // console.log(JSON.parse(_id));
            Users.find({_id:JSON.parse(_id)}).then(data => {
               if(data.length<=0){
                   res.json({"data":"error","message":"login"})
               }else{
                res.json({"data":"ok","message":"success"})
               }
           });
         }else{
            res.json({"data":"error","message":"login"})
         }
  }